package com.ziwei.doushu.core;

import com.ziwei.doushu.model.BirthInfo;
import com.ziwei.doushu.model.ZiweiResult;
import java.util.*;

/**
 * 紫微斗数核心计算类
 */
public class ZiweiCalculator {
    
    // 十二宫位名称
    private static final String[] PALACE_NAMES = {
        "命宫", "父母宫", "福德宫", "田宅宫", "官禄宫", "奴仆宫",
        "迁移宫", "疾厄宫", "财帛宫", "子女宫", "夫妻宫", "兄弟宫"
    };
    
    // 十四主星名称
    private static final String[] MAIN_STARS = {
        "紫微", "天机", "太阳", "武曲", "天同", "廉贞",
        "天府", "太阴", "贪狼", "巨门", "天相", "天梁", "七杀", "破军"
    };
    
    // 时辰对应表
    private static final String[] HOUR_NAMES = {
        "子时", "丑时", "寅时", "卯时", "辰时", "巳时",
        "午时", "未时", "申时", "酉时", "戌时", "亥时"
    };
    
    /**
     * 计算紫微斗数排盘
     */
    public ZiweiResult calculate(BirthInfo birthInfo) {
        ZiweiResult result = new ZiweiResult(birthInfo);
        
        // 计算命宫位置
        int mingGong = calculateMingGong(birthInfo);
        
        // 计算十二宫位
        Map<String, String> palaceInfo = calculatePalaces(mingGong);
        result.setPalaceInfo(palaceInfo);
        
        // 计算主星分布
        Map<String, String> starInfo = calculateMainStars(birthInfo, mingGong);
        result.setStarInfo(starInfo);
        
        // 格局分析
        String patternAnalysis = analyzePattern(starInfo, palaceInfo);
        result.setPatternAnalysis(patternAnalysis);
        
        // 大运流年
        List<String> fortuneInfo = calculateFortune(birthInfo, mingGong);
        result.setFortuneInfo(fortuneInfo);
        
        return result;
    }
    
    /**
     * 计算命宫位置
     */
    private int calculateMingGong(BirthInfo birthInfo) {
        // 根据出生月份和时辰计算命宫
        int month = birthInfo.getMonth();
        int hour = birthInfo.getHour();
        
        // 简化算法：命宫 = (月份 + 时辰) % 12
        int mingGong = (month + hour) % 12;
        return mingGong;
    }
    
    /**
     * 计算十二宫位
     */
    private Map<String, String> calculatePalaces(int mingGong) {
        Map<String, String> palaces = new HashMap<>();
        
        for (int i = 0; i < 12; i++) {
            int palaceIndex = (mingGong + i) % 12;
            palaces.put(PALACE_NAMES[palaceIndex], getPalaceDescription(palaceIndex));
        }
        
        return palaces;
    }
    
    /**
     * 计算主星分布
     */
    private Map<String, String> calculateMainStars(BirthInfo birthInfo, int mingGong) {
        Map<String, String> stars = new HashMap<>();
        
        // 根据生辰八字计算主星位置
        int year = birthInfo.getYear();
        int month = birthInfo.getMonth();
        int day = birthInfo.getDay();
        int hour = birthInfo.getHour();
        
        // 紫微星位置计算
        int ziweiPosition = (year + month + day + hour) % 12;
        stars.put("紫微", PALACE_NAMES[ziweiPosition]);
        
        // 其他主星位置计算（简化算法）
        for (int i = 1; i < MAIN_STARS.length; i++) {
            int starPosition = (ziweiPosition + i * 2) % 12;
            stars.put(MAIN_STARS[i], PALACE_NAMES[starPosition]);
        }
        
        return stars;
    }
    
    /**
     * 格局分析
     */
    private String analyzePattern(Map<String, String> starInfo, Map<String, String> palaceInfo) {
        StringBuilder analysis = new StringBuilder();
        
        // 分析命宫主星
        String mingGongStar = findStarInPalace(starInfo, "命宫");
        if (mingGongStar != null) {
            analysis.append("命宫主星：").append(mingGongStar).append("\n");
            analysis.append(getStarAnalysis(mingGongStar));
        }
        
        // 分析财帛宫
        String caiBoStar = findStarInPalace(starInfo, "财帛宫");
        if (caiBoStar != null) {
            analysis.append("财帛宫主星：").append(caiBoStar).append("\n");
            analysis.append(getWealthAnalysis(caiBoStar));
        }
        
        // 分析官禄宫
        String guanLuStar = findStarInPalace(starInfo, "官禄宫");
        if (guanLuStar != null) {
            analysis.append("官禄宫主星：").append(guanLuStar).append("\n");
            analysis.append(getCareerAnalysis(guanLuStar));
        }
        
        return analysis.toString();
    }
    
    /**
     * 大运流年计算
     */
    private List<String> calculateFortune(BirthInfo birthInfo, int mingGong) {
        List<String> fortune = new ArrayList<>();
        
        // 计算大运起始年龄
        int startAge = calculateStartAge(birthInfo);
        
        // 生成大运信息
        for (int i = 0; i < 8; i++) {
            int age = startAge + i * 10;
            String period = String.format("%d-%d岁", age, age + 9);
            String description = getFortuneDescription(age, mingGong);
            fortune.add(period + "：" + description);
        }
        
        return fortune;
    }
    
    // 辅助方法
    private String getPalaceDescription(int palaceIndex) {
        String[] descriptions = {
            "命宫：主宰人的性格、外貌、才能",
            "父母宫：代表父母、长辈关系",
            "福德宫：代表精神生活、福气",
            "田宅宫：代表不动产、家庭环境",
            "官禄宫：代表事业、工作运势",
            "奴仆宫：代表朋友、下属关系",
            "迁移宫：代表外出、变动运势",
            "疾厄宫：代表健康状况",
            "财帛宫：代表财运、理财能力",
            "子女宫：代表子女、学生关系",
            "夫妻宫：代表婚姻、感情运势",
            "兄弟宫：代表兄弟姐妹关系"
        };
        return descriptions[palaceIndex];
    }
    
    private String findStarInPalace(Map<String, String> starInfo, String palace) {
        for (Map.Entry<String, String> entry : starInfo.entrySet()) {
            if (palace.equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    
    private String getStarAnalysis(String star) {
        Map<String, String> analyses = new HashMap<>();
        analyses.put("紫微", "帝王星，性格高贵，有领导才能，但可能过于自负。");
        analyses.put("天机", "智慧星，聪明机智，善于谋略，但可能多疑。");
        analyses.put("太阳", "光明星，性格开朗，有正义感，但可能过于急躁。");
        analyses.put("武曲", "财星，理财能力强，做事果断，但可能过于固执。");
        analyses.put("天同", "福星，性格温和，人缘好，但可能缺乏进取心。");
        analyses.put("廉贞", "囚星，性格刚烈，有正义感，但可能过于冲动。");
        
        String result = analyses.get(star);
        return result != null ? result : "主星分析：此星主" + star + "，具有相应的性格特征。";
    }
    
    private String getWealthAnalysis(String star) {
        Map<String, String> analyses = new HashMap<>();
        analyses.put("武曲", "财帛宫有武曲星，理财能力强，财运较好。");
        analyses.put("天府", "财帛宫有天府星，善于积累财富，财运稳定。");
        analyses.put("太阴", "财帛宫有太阴星，财运平稳，适合稳健投资。");
        
        String result = analyses.get(star);
        return result != null ? result : "财帛宫主星：" + star + "，财运特征需结合具体分析。";
    }
    
    private String getCareerAnalysis(String star) {
        Map<String, String> analyses = new HashMap<>();
        analyses.put("紫微", "官禄宫有紫微星，适合领导职位，事业运势强。");
        analyses.put("太阳", "官禄宫有太阳星，适合公职或教育行业。");
        analyses.put("武曲", "官禄宫有武曲星，适合金融或技术工作。");
        
        String result = analyses.get(star);
        return result != null ? result : "官禄宫主星：" + star + "，事业运势需结合具体分析。";
    }
    
    private int calculateStartAge(BirthInfo birthInfo) {
        // 简化算法：根据出生年份计算起始年龄
        return 5 + (birthInfo.getYear() % 10);
    }
    
    private String getFortuneDescription(int age, int mingGong) {
        String[] descriptions = {
            "早年运势平稳，学业顺利",
            "青年时期运势上升，事业起步",
            "中年运势旺盛，财运亨通",
            "晚年运势稳定，享受成果"
        };
        
        int index = (age / 20) % descriptions.length;
        return descriptions[index];
    }
}
